#include "EZRPC_ServerPool.h"
#include <algorithm>


bool EZRPC_ServerPool::register_server(google::protobuf::Service* sr)
{
	if (!sr)
		return false;
	auto it = std::find_if(reg_list.begin(), reg_list.end(), [&](const server_info& hs){
		return sr->GetDescriptor()->full_name() == hs.server_name;
	});

	if (it != reg_list.end()){
		assert(1 == 0);
		return false;
	}

	server_info rpc_sr;
	rpc_sr.server = sr;
	rpc_sr.server_name = sr->GetDescriptor()->full_name();
	for (int i = 0; i < sr->GetDescriptor()->method_count(); ++i)
	{
		server_info::method_info rpc_mt;
		rpc_mt.method_desc = sr->GetDescriptor()->method(i);
		rpc_mt.method_name = sr->GetDescriptor()->method(i)->full_name();
		rpc_sr.method_list.emplace_back(rpc_mt);
	}
	reg_list.emplace_back(rpc_sr);
	return true;
}

void EZRPC_ServerPool::unregister_server(google::protobuf::Service* sr)
{
	if (!sr)
		return;
	auto it = std::find_if(reg_list.begin(), reg_list.end(), [&](const server_info& hs){
		return sr->GetDescriptor()->full_name() == hs.server_name;
	});

	if (it != reg_list.end()){
		assert(1 == 0);
		return;
	}
	reg_list.erase(it);
}

google::protobuf::Service* EZRPC_ServerPool::server_desc(const std::string& server_name)
{
	auto it = std::find_if(reg_list.begin(), reg_list.end(), [&](const server_info& hs){
		return server_name == hs.server_name;
	});
	if (it == reg_list.end()){
		return nullptr;
	}
	return it->server;
}

const google::protobuf::MethodDescriptor* EZRPC_ServerPool::method_desc(const std::string& server_name
	, const std::string& method_name)
{
	auto it = std::find_if(reg_list.begin(), reg_list.end(), [&](const server_info& hs){
		return server_name == hs.server_name;
	});
	if (it == reg_list.end()){
		return nullptr;
	}
	auto it1 = std::find_if(it->method_list.begin(), it->method_list.end(), [&](const server_info::method_info& hs){
		return hs.method_name == method_name;
	});
	if (it1 == it->method_list.end()){
		return nullptr;
	}
	return it1->method_desc;
}
